/**
 * Aibton.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package com.aibton.framework.api.auth.util;

import java.lang.annotation.Annotation;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.aibton.framework.api.auth.annotation.Auth;
import com.aibton.framework.api.auth.data.AuthData;
import com.aibton.framework.api.threadLocal.ApiThreadLocalUtils;
import com.aibton.framework.enums.AibtonEnumErrorConfig;
import com.aibton.framework.exception.ExtItemException;
import com.aibton.framework.util.LoggerUtils;

/**
 * 权限处理工具类
 * @author huzhihui
 * @version $: v 0.1 2017 2017/7/28 11:03 huzhihui Exp $$
 */
public class AibtonAuthUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(AibtonAuthUtils.class);

    /**
     * 校验权限
     * @param bean  校验权限输入bean对象也就是api对象
     */
    public static void validateAuth(Object bean) {
        Class<?> objectClass = bean.getClass();
        Annotation[] arrayAno = objectClass.getAnnotations();
        for (Annotation annotation : arrayAno) {
            if (annotation instanceof Auth) {
                Auth authAnno = (Auth) annotation;
                List<AuthData> authDatas = ApiThreadLocalUtils.getAuthDatas();
                List<AuthData> sessionAuthDatas = ApiThreadLocalUtils.getAuthsSession();
                //如果用户没有设置权限，直接返回
                if (CollectionUtils.isEmpty(authDatas)
                    && CollectionUtils.isEmpty(sessionAuthDatas)) {
                    LoggerUtils.info(LOGGER, "用户没有设置Auth");
                    return;
                }
                authDatas = authDatas != null ? authDatas : sessionAuthDatas;
                if (authAnno.auth().length != 0) {
                    Boolean abAuthFlg = false;
                    for (String chechCode : authAnno.auth()) {
                        if (!CollectionUtils.isEmpty(authDatas) && abAuthFlg.equals(false)) {
                            for (AuthData authData : authDatas) {
                                if (authData.getCode().equals(chechCode)) {
                                    abAuthFlg = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (abAuthFlg.equals(false)) {
                        throw new ExtItemException(AibtonEnumErrorConfig.USER_NOT_AUTH);
                    }
                }
            }
        }
    }
}
